﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace WebGetter
{
    class TianYaRule1 : IWebGetRule
    {
        private const string ItemNo = "ItemNo";
        //http://www.tianya.cn/publicforum/content/funinfo/1/2275358.shtml
        private const string MATCHPATTERN = @"http://www\.tianya\.cn/publicforum/content/funinfo/.+";
        private const string GET_CURRENT_URL_FORMAT = @"http://www.tianya.cn/publicforum/content/funinfo/{0}/{1}.shtml";

        public void InitHelper(RegexHelper helper)
        {
            helper.GetByRegexp(Keys.Title, @"<title>(?<val>.+?)</title>");
            helper.GetByRegexp(Keys.PageNo, @"(<em\sclass=.current.>(?<val>\d+)</em>)|(intpage_num\s=\s'(?<val>\d+)';)");
            helper.GetByRegexp(Keys.TotalNo, @"<span>共(?<val>\d+)页</span>");
            helper.GetByRegexp(Keys.NextUrl, @"<a\shref=['""]?(?<val>[^>]+?)['""]?\s?>下一页</a>");
            helper.GetByRegexp(Keys.PageAuthor, @"chrAuthorName\s=\s.(?<val>.+?).;");
            helper.GetByRegexp(Keys.Author, @"(<a\shref=\""/browse/Listwriter\.asp\?vid=\d+&vwriter=(?<val>.+?)(&key=)?\"".+?target=_blank>)|(<a\shref=""http://my\.tianya\.cn/name/(?<val>[^""]+?)"")");

            helper.GetByRegexp(Keys.Content, @"<div\sclass=""post""[^>]+>(?<val>.+?)<div");
            helper.GetByRegexp(Keys.Floor, @"<span\sclass=.floor.>(?<val>.+?)(<sup>|</span>)");
            helper.GetByRegexp(Keys.PostTime, @"日期：(?<val>\d{4}-\d{1,2}-\d{1,2}(\s+\d{1,2}(:\d{1,2}){1,2})?)(</div>|</font>|</td>)");

            helper.GetByRegexp(ItemNo, @"intItem\s=\s.(?<val>.+?).;");
            helper.GetByRegexp(Keys.ArticleId, @"intArticleId\s=\s.(?<val>.+?).;");
            helper.GetByRegexp(Keys.PageUrl, @"strPageUrl\s*=\s*(""|')(?<val>.+?)(""|')(;|//).");
        }

        public string GetCurrentUrl(RegexHelper helper)
        {
            string pageUrl = helper.GetKeyItem(Keys.PageUrl);
            if (!string.IsNullOrEmpty(pageUrl))
            {
                return pageUrl;
            }
            else
            {
                return string.Format(GET_CURRENT_URL_FORMAT,
                    helper.GetKeyItem(ItemNo),
                    helper.GetKeyItem(Keys.PageNo),
                    helper.GetKeyItem(Keys.ArticleId));
            }
        }

        public bool IsMatched(string url)
        {
            return Regex.IsMatch(url, MATCHPATTERN);
        }
    }
}
